///import core.js
///import config.js

/*
	对话框
*/
if(!window['Core']) window.Core = {};

//Core公用函数
Core.Html = {
    GetShadow: function(){
        return '';
        return '<div class="shadow-cor cor-tl"></div><div class="shadow-cor cor-tr"></div><div class="shadow-cor cor-br"></div><div class="shadow-cor cor-bl"></div><div class="shadow-cor cor-t"></div><div class="shadow-cor cor-r"></div><div class="shadow-cor cor-b"></div><div class="shadow-cor cor-l"></div>';
    },
    StopPropagation:function(e){
        Util.Html.StopPropagation(e);
    },
    GetFullIFrame: function(){
        return "";
    //return ($.browser.msie?'<iframe width="100%" height="100%" style="z-index:-1;position:absolute;top:0;left:0;">':"");
    }
};

Core.CONFIG = {
    ActiveClass: "window-current",
    MsgTimeout: 2000
};
Core.DialogBase = function(settings){
    var _temp = '<div class="dialog-box" style="display:none;z-index:1000000002">'+
    Core.Html.GetShadow()+
    '<div class="dialog-title" rel="title_box">'+
    '<strong rel="base_title"></strong>'+
    '<a href="javascript:;" class="close" btn="close">关闭</a>'+
    '</div>'+
    '<div rel="base_content"></div>'+
    '</div>';
    var _box,_cover,_timer, _self = this;
    var _settings = !settings? {}: settings;
    this.Main = $(document.body)
	
    var create = function(win){
        if(!_self.warp){
            _self.warp = $(_temp);
            if(_settings.width){	//判断是否设置宽度
                _self.warp.width(_settings.width);
            }
            $(document.body).append(_self.warp);
            _self.warp.find("[btn]").mousedown(function(e){
                Core.Html.StopPropagation(e);
                return true;
            })
            _self.warp.find("[btn]").click(function(e){
                switch($(this).attr("btn")){
                    case "close":
                        _self.Close();
                        break;
                }
                return false;
            });
            if(_settings.title){
                _self.warp.find("[rel='base_title']").html(_settings.title);
            }
            if(_settings.content){
                _self.warp.find("[rel='base_content']").append(_settings.content);
            }
            Util.Mouse.MoveBox({
                ClickBox: _self.warp.find("[rel='title_box']"),
                Box: _self.warp,
                Outer: _self.Main
            });
            if(_self.Initial){
                _self.Initial();
            }
        }
        if(!_cover){
            _cover = $('<div style="z-index: 1000000001; display: none;background: none repeat scroll 0 0 #fff;_padding-top:40px;height: 100%;left: 0;position: absolute;top: 0;width: 100%;filter:alpha(opacity=0);-moz-opacity:0;opacity:0.0;"><div style="height:100%;width:100%;"></div></div>');
            $(document.body).append(_cover);
            _cover.bind("mousedown",function(){
                if(_timer){
                    window.clearInterval(_timer);
                }
                _timer = window.setInterval(function(){
                    if(_timer_index % 2){
                        _self.warp && _self.warp.addClass(Core.CONFIG.ActiveClass);
                    }
                    else{
                        _self.warp && _self.warp.removeClass(Core.CONFIG.ActiveClass);
                    }
                    _timer_index++;
                    if(_timer_index > (Core.CONFIG.TwinkCount * 2 + 1)){
                        _timer_index = 1;
                        if(_timer){
                            window.clearInterval(_timer);
                        }
                    }
                },Core.CONFIG.TwinkTime);
            });
            
            $(document).on("keydown", function(e){
                if(e.keyCode == 27){
                    if(_cover){
                        _self.Close();
                        return false;
                    }
                }
            })
        }
        Util.Layer.Center(_self.warp,{
            Main: win?win.warp:false
        });
    }
	
    var _timer_index = 1;
	
    this.Open = function(calback,win){
        create(win);
        if(calback){
            calback();
        }
        _cover.show();
        _self.warp.addClass(Core.CONFIG.ActiveClass).show();
        _self.warp.find('[btn="close"]').focus().blur();
    }
	
    this.Close = function(){
        _cover && _cover.hide().remove();
        _self.warp && _self.warp.hide().remove();
        _cover = false;
        _self.warp = false;
    }	
};


/*
    弹窗消息
*/
Core.Message = (function(){
    var _dialog;
    
    /*
    弹窗消息类
    */
    var _MessageModel = function(){
        var _self = this, _initState = false, _callback, _openStatus = false,_dialog_type;
        
        var _content = $('<div class="dialog-contents" style="text-align:left;">'+
                            '<div rel="content"></div>'+
                        '</div>'+
                        '<div class="dialog-bottom">'+
                            '<div class="con">'+
                                '<a class="button" btn="confirm">确定</a>'+
                                '<a class="button btn-gray"  btn="cancel">取消</a>'+
                            '</div>'+
                        '</div>');
        Core.DialogBase.call(this,{
            content: _content, 
            title: '信息提示'
        }); //继承dialog
        
        var setTitle = function(title){
            title && _self.warp.find("[rel='base_title']").html(title);
        }

        //初始化事件
        this.Initial = function(){
            
            
            if(!_initState){
                $(document).bind("keyup", function(e){
                    if(_openStatus){
                        if(e.keyCode == 13){
                            _content.find("[btn='confirm']").click();
                            return false;
                        }
                        else if(e.keyCode == 27){
                            switch(_dialog_type){
                                case 0:
                                    _content.find("[btn='confirm']").click();
                                    break;
                                case 1:
                                    _content.find("[btn='cancel']").click();
                                    break;
                            }

                        }
                    }
                })
            }
        }
        
        var _closeFun = this.Close;
        
        this.Close = function(){
            _closeFun();
            _openStatus = false;
            
        }
        
        this.Show = function(obj){
            _callback = false;
            _self.Open(function(){
                var cancelBtn = _content.find("[btn='cancel']");
                var confirmBtn = _content.find("[btn='confirm']");
                if(obj.confirm_link){
                    confirmBtn.unbind("click").bind("click", function(){
                        if(_callback){
                            _callback(true);
                        }
                        _self.Close();
                        return true;
                    });
                    confirmBtn.attr("href", obj.confirm_link).attr("target", "_blank");
                    
                    cancelBtn.unbind("click").bind("click",function(){
                        var r = true;
                        if(_callback){
                            r = _callback(false);
                        }
                        if(r === false){
                            return false;
                        }
                        _self.Close();
                        return false;
                    })
                }
                else{
                    
                    if(confirmBtn.attr("target")){
                        confirmBtn.removeAttr("target");
                        confirmBtn.attr("href", "javascript:;");
                    }
                    _self.warp.find("[btn]").unbind("click").bind("click",function(){

                        if($(this).attr("btn") != "confirm") {
                            _self.Close();
                            return false;
                        }
                        var r = true;
                        if(_callback){
                            if(obj.input) {
                                _callback(_self,_content);
                            }
                            else r = _callback($(this).attr("btn") == "confirm");
                        }
                        if(!obj.input) _self.Close();
                        return false;
                    })
                }
                if(obj.confirm_text){
                    confirmBtn.html(obj.confirm_text);
                }
                else{
                    confirmBtn.html("确定");
                }
                
                if(obj.cancel_text){
                    cancelBtn.html(obj.cancel_text);
                }
                else{
                    cancelBtn.html("取消");
                }
                _callback = obj.callback;
                setTitle(obj.title);
                if(obj.dialog_type == undefined){
                    obj.dialog_type = 0;
                }
                if(!obj.type){
                    obj.type = "hint"
                }
                var html_temp;

                if(obj.input) {
                    html_temp = '<div class="dialog-hint">{label}<input type="text" class="input-text" value="{value}" vali="{vali}" errormsg="{errormsg}" /><span class="onShow">{errormsg}</span> </div>';
                }
                else {
                    html_temp = '<i class="icon-{type}"></i>' + 
                (obj.content?'<div class="dialog-hint">{content}</div>' : "");
                }

                var con = _content.find("[rel='content']");
                con.html(UtilLin.uiCommon.formatTpl(html_temp,obj));
                confirmBtn.removeClass("btn-orange");
                switch(obj.dialog_type){
                    case 0:
                        //cancelBtn.hide();
                        break;
                    case 1:
                        //cancelBtn.hide();
                        break;
                }
                _dialog_type = obj.dialog_type;
                _openStatus = true;
            },obj.win);
        }
    }
    
    var init = function(){
        if(!_dialog){
            _dialog = new _MessageModel();
        }
    }
    
    var _alertTimer;
    
    return {
        Confirm: function(obj){
            init();
            obj.dialog_type = 1;
            _dialog.Show(obj);
        },
        Alert: function(obj){
            init();
            obj.dialog_type = 0;
            _dialog.Show(obj);
            if(obj.timeout){
                _alertTimer = window.setTimeout(function(){
                    Core.Message.Hide();
                }, obj.timeout);
            }
        },
        Hide: function(){
            if(_alertTimer){
                window.clearTimeout(_alertTimer);
            }
            if(_dialog){
                _dialog.Close();
            }
        }
    }
})();

//iframe提示框
;(function(){
    var mod = function(actions){
        var _content = $('<div class="dialog-frame"><iframe style="background:#fff;" id="myiframe" frameborder=0 src=""></iframe></div>'), _self = this;
        //<div class="dialog-bottom"><div class="con"><a class="button" btn="confirm">确定</a><a class="button btn-gray" btn="cancel">取消</a></div></div>
        var _top = Util.Override(Core.DialogBase, _self, {
            Initial: function(){
                if($.browser.mozilla){
                    _content.find("iframe").on("load", function(){
                        try{
                            var win = $(this.contentWindow);
                            $(win).on("keydown", function(e){
                                if(e.keyCode == 27){
                                    return false;
                                }
                            });
                        }catch(e){}
                    });
                }
            },
            GetIframe: function(){
                return _content[0];
            },
            Show: function(url){
                _top.Open(function(){
                    _content.find("iframe").off("load").on("load", function(){
                        if(actions && actions['ready']){
                            var ifr = this;
                            window.setTimeout(function(){
                                actions['ready'](ifr.contentWindow);
                            }, 10);
                        }
                    });
                });
                _content.find("iframe").attr("src", url);
            },
            Reset: function(width, height, notcenter){
                if(width){
                    _self.warp.width(width);
                    _content.find("iframe").width(width);
                }
                if(height){
                    _content.height(height);
                    _content.find("iframe").height(height);
                }
                if(!notcenter){
                    Util.Layer.Center(_self.warp);
                }
            },
            Close: function(doHide){
                actions && actions["close"] && actions["close"](doHide);
                window.setTimeout(function(){
                    _content.find("iframe").attr("src", "");
                    _top.Close();
                },10);

            },
            ResetTitle: function(title, confirm){
                _self.warp.find('[rel="base_title"]').html(title);
                if(confirm) {
                    if(!_content.nextAll(".dialog-bottom").length) {
                        _content.after('<div class="dialog-bottom"><div class="con"><a class="button" btn="confirm">确定</a><a class="button btn-gray" btn="cancel">取消</a></div></div>');
                            _content.parent().on("click", "[btn]", function (){
                            if($(this).attr("btn") == "confirm") {
                                Core.FrameDG.confirm(_content.find("iframe")[0].contentWindow);
                            }
                            else {
                                Core.FrameDG.Close();
                            }
                        })
                    }
                    
                }
            }
        }, {
            content: _content, 
            title: "新窗口"
        });
    }
    /*
    * IFrame 对话窗
    */
    Core.FrameDG = (function(){
        var _mod, _doHandler, _hideBack = false, _hideBackData, _ready;
        
        return {
            IsOpen: function(){
                if(_mod){
                    return _mod.warp.length;
                }
                return false;
            },
            GetIframe: function(){
                if(_mod){
                    return _mod.GetIframe();
                }
                else{
                    return false;
                }
            },
            Reset: function(width, height, notcenter){
                if(_mod){
                    _mod.Reset(width, height, notcenter);
                }
            },
            ResetTitle: function(title){
                if(_mod){
                    _mod.ResetTitle(title);
                }
            },
            Open: function(url, setting){
                if(setting.callback){
                    _doHandler = setting.callback;
                }
                else{
                    _doHandler = false;
                }

                if(setting.ready){
                    _ready = setting.ready;
                }
                else{
                    _ready = false;
                }

                if(!_mod){
                    _mod = new mod({
                        ready: function(win){
                            _ready && _ready(win);
                        },
                        close: function(doHide){
                            if(!doHide){
                                if(_hideBack){
                                    _doHandler && _doHandler(_hideBackData);
                                }
                            }
                        }
                    });
                }
                _hideBackData =  null;
                _hideBackData = setting.hide_data;

                _hideBack = setting.is_hide_back;
                _mod.Show(url);

                if(setting){
                    _mod.Reset(setting.width, setting.height);
                    if(setting.btn) {
                        _mod.ResetTitle(setting.title? setting.title: "新窗口", true);
                    }
                    else _mod.ResetTitle(setting.title? setting.title: "新窗口");
                }
            },
            Close: function(data){
                if(_mod){
                    if(_doHandler) _doHandler(data);
                    _mod.Close(true);
                }
            },
            confirm:function (data) {
                if(_mod){
                    if(_doHandler) _doHandler(data);
                }
            },
            Hide: function(){
                if(_mod){
                    _mod.Close();
                }
            }
        }
    })();
})();

/*
    迷你信息提示
*/
Core.MinMessage = (function(){
    var _temp = '<div class="popup-hint" style="z-index:9999999999;">'+
    '<i class="" rel="type"></i>'+
    '<em class="sl"><b></b></em>'+
    '<span rel="con"></span>'+
    '<em class="sr"><b></b></em>'+
    '</div>';
    var _cache = {
        Type:{
            "suc": "hint-icon hint-suc-m",
            "war": "hint-icon hint-war-m",
            "err": "hint-icon hint-err-m",
            "load": "hint-loader",
            "inf": "hint-icon hint-inf-m"
        }
    }, _dom, _timer;
    
    //创建消息DOM
    var create = function(text,type){
        if(!_dom){
            _dom = $(String.format(_temp,text));
            $(document.body).append(_dom);
        }
        _dom.find("[rel='con']").html(text);
        var icon = _dom.find("[rel='type']");
        for(var k in _cache.Type){
            icon.removeClass(_cache.Type[k]);
        }
        icon.addClass(_cache.Type[type]);
    }
    
    //隐藏
    var hide = function(){
        if(_timer){
            window.clearTimeout(_timer);
        }
        if(_dom){
            _dom.hide();
        }
    }

    return {
        Show: function(obj){
            if(!obj.type){
                obj.type = "war";
            }
            create(obj.text,obj.type);
            Util.Layer.Center(_dom,{
                Main:obj.window?obj.window.warp:false
            });
            _dom.show();
            if(_timer){
                window.clearTimeout(_timer);
            }
            if(obj.timeout){
                _timer = window.setTimeout(hide,obj.timeout);
            }
        },
        Hide: function(){
            hide();
        }
    }
})();


/*选择文件对话框*/
Core.FileSelectDG = (function(){
    
    var _dirCacheAid, _dirCacheCid, _dirCacheCname, _dirCachePath, _paths, _api = false;
    
    
    var _model = function(){
        var _self = this, _cache = {
            disClass: "btn-disabled"
        };
        
        
        var _content = $('<div>'+
                            '<div class="dialog-frame" style="height:450px">'+
                                '<iframe src="" frameborder="0" rel="js_iframe" style="height:450px"></iframe>'+
                            '</div>'+
                            '<div class="dialog-bottom">'+
                                '<div class="con">'+
                                    '<a href="javascript:;" class="button" btn="confirm">确定</a>'+
                                '</div>'+
                            '</div>'+
                        '</div>');
        
                    
        Core.DialogBase.call(this, {
            title: '请选择文件', 
            content: _content, width: 700
        });
		
        var _frame = _content.find("[rel='js_iframe']");
        
        var changeURL = function(aid, cid, opt){
            var select = 0, filter = "", nf = "", select_dir = '', pub = '';
            if(opt){
                select = opt.select_one?1:0;
                filter = opt.filter?opt.filter: "";
                nf = opt.nf? opt.nf: "";
                select_dir = opt.select_dir?1:0;
                pub = opt.pub? opt.pub : '';
            }
            _api = false;
            var url = "/disk/?ac=select_public_file&ajax=1&pub="+pub+"&select="+select + "&nf=" + nf +"&filter="+filter+"&select_dir="+select_dir + "&cid=" + cid + "&_t=" + new Date().getTime();
            _frame.attr("src",""); 
            _frame.attr("src",url);
        }
		
        this.Initial = function(){
            _self.warp.addClass("file-select");
            window["DBLClick_BACK"] = function(node){
                _cache.list = [node];
                _content.find("[btn='confirm']").click();
                
            }
            
            _self.warp.find("[rel='check_all']").on("click", function(){
                if(_api.SelectAll){
                    $(this).attr('checked')? _api.SelectAll() : _api.CancelSelect();
                }
                
            })
            
            _content.find("[btn]").off("click").on("click",function(){
                switch($(this).attr("btn")){
                    case "add_dir":
                        if(_dirCacheAid){
                            Core.Dir.Create(_dirCacheAid, _dirCacheCid, function(r){
                                if(r.state){
                                    changeURL(_dirCacheAid, r.cid, {
                                        select_one: _cache.select_one,
                                        filter: _cache.filter,
                                        nf: _cache.nf,
                                        qid_file: _cache.qid_file,
                                        pub: _cache.pub
                                    });
                                }
                                
                            });
                        }
                        break;
                    case "confirm":
                        if(_cache.nf){
                            if(_dirCacheAid === false){
                                Core.MinMessage.Show({
                                    text: "请等待进入文件夹", 
                                    timeout: Core.CONFIG.MsgTimeout, 
                                    window: _self
                                });
                                return;
                            }
                        }
                        else{
                            if(!_cache.list || !_cache.list.length){

                                Core.MinMessage.Show({
                                    text: "请选择文件", 
                                    timeout: Core.CONFIG.MsgTimeout, 
                                    window: _self
                                });
                                return;
                            }
                        }
                        
                        switch(_cache.type){
                            case "msg":
                                var arr = [];
                                
                                if(_cache.nf){
                                    arr.push({
                                        aid: _dirCacheAid,
                                        cid: _dirCacheCid,
                                        cname: _dirCacheCname,
                                        path: _dirCachePath
                                    })
                                }
                                else{
                                    for(var i = 0, len = _cache.list.length; i < len; i++){

                                        var item = _cache.list[i];

                                        if(item.attr("file_type") == "1"){
                                            arr.push({
                                                file_id: item.attr("file_id"),
                                                file_size: item.attr("file_size"),
                                                file_name: item.find('[field="file_name"]').attr("title"),
                                                aid: item.attr("area_id"),
                                                cid: item.attr("p_id"),
                                                ico: item.attr("ico"),
                                                sha1: item.attr("sha1"),
                                                pick_code: item.attr("pick_code"),
                                                path: item.attr("path")
                                            });
                                        }
                                        else{
                                            if(_cache.select_dir){
                                                arr.push({
                                                    aid: item.attr("area_id"),
                                                    cid: item.attr("cate_id"),
                                                    cate_name: item.attr("cate_name"),
                                                    pick_code: item.attr("pick_code"),
                                                    is_dir: 1
                                                });
                                            }
                                            else{
                                                arr.push({
                                                    aid: item.attr("area_id"),
                                                    cid: item.attr("cate_id")
                                                });
                                            }
                                        }

                                    }
                                }
                                
                                _self.Callback && _self.Callback(arr, false);
                                window.setTimeout(function(){
                                    _self.Close();
                                },10);
                                break;
                            default:
                                _self.Callback && _self.Callback(_cache.list, false);
                                window.setTimeout(function(){
                                    _self.Close();
                                },10);
                                break;
                        }
						
                        break;
                    case "cancel":
                        _self.Close();
                        break;
                }
                return false;
            });
            
            var oldAid = 1, oldCid = 0;
            
            var oldCookie = Util.Cookie.get("SEL_F_DIR");
            if(oldCookie){
                var oldArr = oldCookie.split("|");
                if(oldArr.length == 2){
                    oldAid = Number(oldArr[0]);
                    oldCid = Number(oldArr[1]);
                }
            }
            
            if(_cache.nf){
                _self.warp.find("[btn='add_dir']").show();
            }
            else{
                _self.warp.find("[btn='add_dir']").hide();
            }
            
            var copyInput = _self.warp.find("input[rel='copy']");
            copyInput.attr("checked", false);
            if(_cache.show_copy){
                _self.warp.find("[rel='copy']").show();
            }
            else{
                _self.warp.find("[rel='copy']").hide();
            }
            
            if(_cache.qid_file){
                _self.warp.find("[btn='add_dir']").hide();
            }
            
            if(_cache.qid_file){
                oldAid = 999;
                oldCid = 0;
            }
            else{
                if(Number(oldAid) == 999){
                    oldAid = 1;
                    oldCid = 0;
                    Util.Cookie.set("SEL_F_DIR", "");
                }
            }
            
            changeURL(oldAid, oldCid, {
                select_one: _cache.select_one,
                filter: _cache.filter,
                nf: _cache.nf,
                qid_file: _cache.qid_file,
                select_dir: _cache.select_dir,
                pub: _cache.pub
            });
        }
        
        this.Setting = function(obj){
            if(obj){
                for(var k in obj){
                    _cache[k] = obj[k];
                }
            }
        }
        
        var _closeEvent = _self.Close;
        this.Close = function(){
            _frame.attr("src","");
            _closeEvent();
            _self.Callback = false;
        }
        
        var _openEvent = _self.Open;
        this.Open = function(){
            _dirCacheAid = false;
            _dirCacheCid = false;
            
            _openEvent();
            
            if(_cache.nf){
                _self.warp.find('[rel="base_title"]').html("双击打开您要"+_cache.select_txt+"的目标文件夹");
                _self.warp.find('[btn="confirm"]').html(_cache.btn_txt);
                _self.warp.find("[rel='check_all']").hide();
            }
            else{
                _self.warp.find("[rel='check_all']").show();
                _self.warp.find('[rel="base_title"]').html("请选择文件");
                _self.warp.find('[btn="confirm"]').html("确定");
            }
            
        }
		
        this.Set = function(arr){
            _cache.list = arr;
        }
		
        this.Callback = false;
    }
	
    var _DG;
    return {
        OpenByMsg: function(callback, opt){
            if(!_DG){
                _DG = new _model();
            }

            var setting = {
                type: "msg"
            };

            if(opt){
                setting["select"] = opt.select? 1: 0;
                setting["filter"] = opt.filter?opt.filter:"";
                setting["select_dir"] = opt.select_dir?1:0;
                setting["pub"] =  opt.pub?1:0;
            }
            _DG.Setting(setting);

            _DG.Open();
            _DG.Callback = callback;
        },
        Open: function(callback, opt){
            if(!_DG){
                _DG = new _model();
            }
            
            var setting = {
                type: "msg"
            };

            if(opt){
                
                setting["select"] = opt.select? 1: 0;
                
                setting["filter"] = opt.filter?opt.filter:"";
                
                setting["nf"] = opt.nf? opt.nf : "";
                
                setting["qid_file"] = opt.qid_f? opt.qid_f: '';
                
                setting["select_dir"] = opt.select_dir?1:0;
                
                setting["pub"] =  opt.pub?1:0;
                
                setting['btn_txt'] = opt.btn_txt? opt.btn_txt:'移动到这里';
                setting['select_txt'] = opt.select_txt? opt.select_txt:'移动';
                
                setting["show_copy"] = opt.show_copy;
                setting["select_one"] = opt.select_one;
            }
            _DG.Setting(setting);

            _DG.Open();
            _DG.Callback = callback;
        },
        Show: function(users, callback){
            if(!_DG){
                _DG = new _model();
            }
            _DG.Setting({
                users:users, 
                type: "send"
            });
            _DG.Open();
            _DG.Callback = callback;
        },
        Select: function(arr){
            if(_DG){
                _DG.Set(arr);
            }
        },
        MarkDir: function(aid, cid){
            if(Number(aid) != 999){
                Util.Cookie.set("SEL_F_DIR", aid + "|" + cid, 24);
            }
        },
        SelectDir: function(aid, cid, cname, path){
            _dirCacheAid = aid;
            _dirCacheCid = cid;
            _dirCacheCname = cname;
            _dirCachePath = path;
        },
        BackPaths: function(paths){
            _paths = paths
        },
        MainAPI: function(api){
            _api = api;
            if(_DG){
                _DG.warp.find("input[rel='check_all']").attr("checked", false);
            }
        },
        GetBackPaths: function(){
            return _paths;
        },
        Close: function(){
            if(_DG){
                _DG.Close();
            }
        }
    }
})();
